package com.zhuhjay.ruiji.filter;

import com.alibaba.fastjson.JSON;
import com.zhuhjay.ruiji.common.BaseContext;
import com.zhuhjay.ruiji.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ZhuHJay
 * @date 2022/5/15 21:24
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    /** 路径匹配器, 支持通配符 **/
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    /** 放行的路径 **/
    private static final String[] PERMIT_URLS = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/favicon.ico",
            "/user/sendMeg",
            "/user/login"
    };

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 获取本次请求的uri
        String requestUri = req.getRequestURI();
        // 判断请求是否需要处理
        // 如果不需要处理, 则直接放行
        if( check(requestUri) ){
            log.warn("请求拦截放行: {}", requestUri);
            chain.doFilter(request, response);
            return;
        }
        // 判断后台用户是否登录, 如果登录那么就放行
        Long empId = (Long) req.getSession().getAttribute("employee");
        if( empId != null ){
            log.warn("已登录: 请求拦截放行: {}", requestUri);
            // 将登录用户的id存放到当前线程的存储空间中, 以备后续使用
            BaseContext.setCurrent(empId);
            chain.doFilter(request, response);
            return;
        }
        // 判断移动端用户是否登录, 如果登录那么就放行
        Long userId = (Long) req.getSession().getAttribute("user");
        if( userId != null ){
            log.warn("已登录: 请求拦截放行: {}", requestUri);
            // 将登录用户的id存放到当前线程的存储空间中, 以备后续使用
            BaseContext.setCurrent(userId);
            chain.doFilter(request, response);
            return;
        }
        log.warn("请求拦截: {}", requestUri);
        // 通过数据流方式响应数据, 告诉客户端用户尚未登陆
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 判断本次请求是否需要放行
     * @param requestUri uri路径
     * @return
     */
    private boolean check(String requestUri){
        for (String permitUrl : PERMIT_URLS) {
            if( PATH_MATCHER.match(permitUrl, requestUri) ){
                return true;
            }
        }
        return false;
    }
}
